<?php
/**
 * Created by PhpStorm.
 * User: harlenh-mac
 * Date: 2017/2/9
 * Time: 下午10:16
 */

namespace app\admin\controller;

use app\admin\model\Files as FilesModel;

/**
 * 上传内容管理 - 控制器。 比如 图片-文件-等资源
 * Class Upload
 * @package app\admin\controller
 */
class Upload extends BaseController
{
    public function index()
    {
        $list = FilesModel::paginate(20);
        $this->assign([
            'list' => $list,
            'page' => $list->render(),
        ]);

        return $this->fetch();
    }

    /**
     * 上传文件控制器。可能需要移动到公共方法里面
     * @return \think\response\Json
     */
    public function fileupload()
    {
        $file = request()->file();
        foreach ($file as $f) {
            if (!is_object(($f))) {
                return json(['code' => 0, 'msg' => '上传信息获取失败']);
            }
            //TODO::验证文件大小，等等
            //移动文件到
            $upload_path = 'public' . DS . 'uploads';
            //echo ROOT_PATH . $upload_path;die;
            $info = $f->validate([])->move(ROOT_PATH . $upload_path);

            if ($info) {
                $FilesModel = new FilesModel;
                $url = DS . $upload_path . DS . $info->getSaveName();
                $FilesModel->data([
                    'extension' => $info->getExtension(),
                    'save_name'      => $info->getSaveName(),
                    'name' => basename($url),
                    'url'       => $url,
                    'size'      => $info->getSize(),
                ]);

                if ($FilesModel->save()) {
                    $id = $FilesModel->getLastInsID();

                    return json(['code' => 1, 'msg' => lang('success'), 'data' => ['id' => $id, 'url' => $url]]);
                } else {
                    return json(['code' => 0, 'msg' => $FilesModel->getError()]);
                }

            } else {
                return json(['code' => 0, 'msg' => $file->getError()]);
            }
        }

        return json(['code' => 0, 'msg' => $file->getError()]);
    }
}